﻿using PLCWpfTest.Common.Extensions;
using System.Threading.Tasks;
using YWM;
using YWM.Common.Exceptions;
using YWM.Common.Extensions;
using YWM.Dto;

namespace PLCWpfTest.Common
{
    public abstract class OperationViewModel : BaseViewModel
    {
        /// <summary>
        /// 是否添加操作
        /// </summary>
        public bool IsAdd { get; set; } = true;

        private string _title;
        /// <summary>
        /// 标题
        /// </summary>
        public string Title
        {
            get
            {
                if (_title.IsNullOrWhiteSpace())
                {
                    _title = IsAdd ? Lang["添加"] : Lang["编辑"];
                }
                return _title;
            }
            set
            {
                _title = value;
            }
        }

        /// <summary>
        /// 确定命令
        /// </summary>
        public AsyncRelayCommand<(IEntityDto, DatabaseMethod)> OkCommand { get; set; }

        public OperationViewModel()
        {
            OkCommand = YApp.Resolve<AsyncRelayCommand<(IEntityDto, DatabaseMethod)>>();
            OkCommand.BeforeCanExecute += OkCommand_BeforeCanExecute;
            OkCommand.BeforeExecute += OkCommand_BeforeExecute;
            OkCommand.Executing += OkCommand_Executing;
            OkCommand.UnexecutedFriendlyException += OkCommand_UnexecutedFriendlyException;
        }

        /// <summary>
        /// 确定命令是否可执行之前事件
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        protected virtual bool OkCommand_BeforeCanExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 确定命令执行之前事件
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        protected virtual bool OkCommand_BeforeExecute(object parameter)
        {
            return true;
        }

        /// <summary>
        /// 确定命令执行中事件
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private async Task<(IEntityDto, DatabaseMethod)> OkCommand_Executing(object parameter)
        {
            IEntityDto entityDto = await OkAsync(parameter);
            return (entityDto, IsAdd ? DatabaseMethod.Insert : DatabaseMethod.Update);
        }

        /// <summary>
        /// 确定异步抽象方法
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        protected abstract Task<IEntityDto> OkAsync(object parameter);

        /// <summary>
        /// 确定命令未执行的友好异常事件
        /// </summary>
        /// <param name="ex"></param>
        protected virtual void OkCommand_UnexecutedFriendlyException(FriendlyException ex)
        {
            OkCommand.ShowError(ex.Message);
        }
    }
}
